package com.wanli.storemobile.homepage;


import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanli.storemobile.R;
import com.wanli.storemobile.base.BaseFragment;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.EBankStoreDataContacts;
import com.wanli.storemobile.bean.IdCardBean;
import com.wanli.storemobile.bean.ImageBean;
import com.wanli.storemobile.bean.StoreDeatilsBean;
import com.wanli.storemobile.event.StoreDataEvent;
import com.wanli.storemobile.event.StoreNextEvent;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.Base64BitmapUtil;
import com.wanli.storemobile.utils.DateTimeUtil;
import com.wanli.storemobile.utils.GlideEngine;
import com.wanli.storemobile.utils.GlideUtils;
import com.wanli.storemobile.utils.PermissionsManager;
import com.wanli.storemobile.utils.SPManager;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.SwitchView;

import static android.app.Activity.RESULT_OK;

/**
 * 公司信息
 */
public class EBankStoreContactsFragment extends BaseFragment {
    public static final String TITLE_TYPE = "type";
    public static final String MERCHANT_ID = "merchant_id";
    public static final String QUICK_INCOME = "quick_income";
    @BindView(R.id.ic_prcture_5)
    ImageView icPrcture5;
    @BindView(R.id.iv_picture_demo_5)
    ImageView ivPictureDemo5;
    @BindView(R.id.ic_prcture_6)
    ImageView icPrcture6;
    @BindView(R.id.iv_picture_demo_6)
    ImageView ivPictureDemo6;
    @BindView(R.id.edit_legal_name)
    EditText editLegalName;
    @BindView(R.id.edit_id_number)
    EditText editIdNumber;
    @BindView(R.id.switchview)
    SwitchView switchview;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.ll_start_time)
    LinearLayout llStartTime;
    @BindView(R.id.view_end_time)
    View viewEndTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.ll_end_time)
    LinearLayout llEndTime;
    @BindView(R.id.ll_company)
    LinearLayout llCompany;
    @BindView(R.id.tv_commit)
    TextView tvCommit;


    private String type;
    private String start_time;
    private String end_time;
    private int timeType = 1;
    private Calendar selectedDate;
    private Gson mGson = new Gson();
    private StoreDeatilsBean.DataBean storeBean;
    private String merchant_id;
    private int quick_income;

    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private List<LocalMedia> mediaList = new ArrayList<>();
    private IHomePageModel homePageModel = new HomePageModelImpl();

    private String prctureDemo5 = "https://wnb-dc.oss-cn-qingdao.aliyuncs.com/resources/idcard.jpeg";
    private String prctureDemo6 = "https://wnb-dc.oss-cn-qingdao.aliyuncs.com/resources/shenfenzhengfanmian.jpg";
    //1 2 3 4 5 6 7 8  20  21 22
    private int imgTpye = 1;
    private String imgPath5, imgPath6;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ebank_store_contacts, container, false);
        ButterKnife.bind(this, view);
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getString(TITLE_TYPE);
            StoreDataEvent dataEvent = EventBus.getDefault().getStickyEvent(StoreDataEvent.class);
            if (dataEvent != null) {
                storeBean = dataEvent.getDataBean();
            }
            merchant_id = bundle.getString(MERCHANT_ID);
            quick_income = bundle.getInt(QUICK_INCOME);
        }
        initView();
        initData();
        return view;
    }

    private void initView() {
        permissionsManager = new PermissionsManager(mActivity);
        selectedDate = Calendar.getInstance();
        switchview.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                llEndTime.setVisibility(View.GONE);
                viewEndTime.setVisibility(View.GONE);
                switchview.setOpened(true);
                tvEndTime.setText("2099-12-31");
            }

            @Override
            public void toggleToOff(SwitchView view) {
                llEndTime.setVisibility(View.VISIBLE);
                viewEndTime.setVisibility(View.VISIBLE);
                switchview.setOpened(false);
            }
        });

        GlideUtils.loadImage(mActivity, ivPictureDemo5, prctureDemo5);
        GlideUtils.loadImage(mActivity, ivPictureDemo6, prctureDemo6);
    }


    public void initData() {
        if (storeBean != null) {
            imgPath5 = storeBean.getLegal_id_card_front_pic();
            imgPath6 = storeBean.getLegal_id_card_back_pic();

            if (!TextUtils.isEmpty(imgPath5)) {
                GlideUtils.loadImage(mActivity, icPrcture5, imgPath5);
            }
            if (!TextUtils.isEmpty(imgPath6)) {
                GlideUtils.loadImage(mActivity, icPrcture6, imgPath6);
            }

            editLegalName.setText(storeBean.getContact_name());
            if (!TextUtils.isEmpty(storeBean.getContact_name())) {
                editLegalName.setSelection(storeBean.getContact_name().length());
            }

            editIdNumber.setText(storeBean.getLegal_id_card_no());
            if (!TextUtils.isEmpty(storeBean.getLegal_id_card_no())) {
                editIdNumber.setSelection(storeBean.getLegal_id_card_no().length());
            }

            if (TextUtils.isEmpty(storeBean.getLegal_id_card_end())) {
                llEndTime.setVisibility(View.GONE);
                viewEndTime.setVisibility(View.GONE);
                switchview.setOpened(true);
                tvEndTime.setText("2099-12-31");
            }

            tvStartTime.setText(storeBean.getLegal_id_card_start());
            tvEndTime.setText(storeBean.getLegal_id_card_end());
        }
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && !isVisibleToUser) {
            Log.d("---", "2222222222222222");

            EBankStoreDataContacts dataCompany = new EBankStoreDataContacts();
            dataCompany.setContact_name(editLegalName.getText().toString());
            dataCompany.setLegal_id_card_no(editIdNumber.getText().toString());
            dataCompany.setLegal_id_card_start(tvStartTime.getText().toString());
            dataCompany.setLegal_id_card_end(tvEndTime.getText().toString());
            dataCompany.setLongTime(switchview.isOpened());
            dataCompany.setLegal_id_card_front_pic(imgPath5);
            dataCompany.setLegal_id_card_back_pic(imgPath6);

            SPManager.getInstance().saveStoreCompany(mGson.toJson(dataCompany));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.ic_prcture_5, R.id.ic_prcture_6, R.id.ll_start_time, R.id.ll_end_time, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ic_prcture_5:
                imgTpye = 5;
                showPictureSelectorDialog();
                break;
            case R.id.ic_prcture_6:
                imgTpye = 6;
                showPictureSelectorDialog();
                break;
            case R.id.ll_start_time:
                if (!TextUtils.isEmpty(tvStartTime.getText().toString())) {
                    selectedDate.setTime(DateTimeUtil.parse(tvStartTime.getText().toString()));
                }
                timeType = 1;
                selectTime();
                break;
            case R.id.ll_end_time:
                if (!TextUtils.isEmpty(tvEndTime.getText().toString())) {
                    selectedDate.setTime(DateTimeUtil.parse(tvEndTime.getText().toString()));
                }
                timeType = 2;
                selectTime();
                break;
            case R.id.tv_commit:
                EventBus.getDefault().post(new StoreNextEvent(2));
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }

    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                if (isDestroy()) {
                    return;
                }
                ToastUtil.showShort("上传成功");
                if (imgTpye == 5) {
                    imgPath5 = bean.getData();
                    GlideUtils.loadImage(mActivity, icPrcture5, imgPath);
                    requestAliIdCard(bean.getData(), "face");
                } else if (imgTpye == 6) {
                    imgPath6 = bean.getData();
                    GlideUtils.loadImage(mActivity, icPrcture6, imgPath);
                    requestAliIdCard(bean.getData(), "back");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAliIdCard(String imgPath, String side) {
        ViewLoading.showProgress(mActivity, "识别中......");
        homePageModel.requestAliIdCard(imgPath, side, new DataCallBack<IdCardBean>() {
            @Override
            public void onSuccessful(IdCardBean bean) {
                if (bean.getData() != null && bean.getData().isSuccess()) {
                    ToastUtil.showShort("识别成功");
                    if ("face".equals(side)) {
                        editLegalName.setText(bean.getData().getName());
                        editIdNumber.setText(bean.getData().getNum());
                        if (!TextUtils.isEmpty(bean.getData().getNum())) {
                            editIdNumber.setSelection(bean.getData().getNum().length());
                        }
                    } else {
                        if (!TextUtils.isEmpty(bean.getData().getStart_date())) {
                            tvStartTime.setText(DateTimeUtil.format(DateTimeUtil.parse1(bean.getData().getStart_date())));
                        }
                        if (!TextUtils.isEmpty(bean.getData().getEnd_date())) {
                            if ("长期".equals(bean.getData().getEnd_date())) {
                                switchview.setOpened(true);
                                llEndTime.setVisibility(View.GONE);
                                viewEndTime.setVisibility(View.GONE);
                                tvEndTime.setText("2099-12-31");
                            } else {
                                llEndTime.setVisibility(View.VISIBLE);
                                viewEndTime.setVisibility(View.VISIBLE);
                                switchview.setOpened(false);
                                tvEndTime.setText(DateTimeUtil.format(DateTimeUtil.parse1(bean.getData().getEnd_date())));
                            }
                        }
                    }

                } else {
                    ToastUtil.showShort("识别失败，请输入");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private TimePickerView pvTime;

    public void selectTime() {
        //这里可以更改参数，有好多类型
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        endDate.set(2099, 11, 31);
        pvTime = new TimePickerBuilder(mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (timeType == 1) {
                    start_time = DateTimeUtil.format(date);
                    tvStartTime.setText(start_time);
                } else {
                    end_time = DateTimeUtil.format(date);
                    tvEndTime.setText(end_time);
                }
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2)
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvTime.show();
    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(EBankStoreContactsFragment.this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(EBankStoreContactsFragment.this)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }
}
